package com.network.server;

import java.io.*;
import java.net.Socket;

public class ServerReaderThread extends Thread {

    private Socket socket;

    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 获取客户端的输入流
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);

            // 循环等待客户端的消息
            while (true) {
                try {

                    //读取到消息广播到所有在线的客户端
                    String str = dis.readUTF();
                    sendMsgToAll(str);
                    System.out.println(str);
                } catch (IOException e) {
                    // 离线将连接移除onlineSockets
                    System.out.println(socket.getRemoteSocketAddress() + "离线了");
                    ServerService.onlineSockets.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void sendMsgToAll(String msg) throws IOException {
        for (Socket onlineSocket : ServerService.onlineSockets) {
            // 接收一个客户端的消息，发送到其他客户端
            OutputStream os = onlineSocket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(msg);
            dos.flush();
        }
    }
}
